<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card>
      <!--搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入姓名" v-model="queryInfo.query" clearable
                    @clear="queryInfo.pagenum=1;getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="queryInfo.pagenum=1;getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表表格渲染区域-->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!--使用插槽渲染状态-->
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!--使用插槽渲染操作按钮-->
          <template v-slot="scope">
            <el-tooltip effect="dark" content="修改" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini"
                         @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini"
                         @click="removeUserById(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"
                         @click="showAssignRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 3, 4]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
      <!--添加用户对话框-->
      <el-dialog
          title="添加用户"
          :visible.sync="addUserDialogVisible"
          width="30%"
          @close="addUserDialogClosed()"
          :close-on-click-modal="false">
        <!--内容主体区-->
        <el-form ref="addUserForm" :model="addUserForm" :rules="addUserFormRules" label-width="70px"
                 status-icon>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" clearable></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" clearable></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addUserForm.mobile" clearable></el-input>
          </el-form-item>
        </el-form>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </span>
      </el-dialog>
      <!--修改用户对话框-->
      <el-dialog
          title="修改用户信息"
          :visible.sync="editUserDialogVisible"
          width="30%"
          @close="editUserDialogClosed()"
          :close-on-click-modal="false">
        <!--内容主体区-->
        <el-form ref="editUserForm" :model="editUserForm" :rules="editUserFormRules" label-width="70px"
                 status-icon>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editUserForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserForm.email" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserForm.mobile" clearable></el-input>
          </el-form-item>
        </el-form>
        <!--底部区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser()">确 定</el-button>
        </span>
      </el-dialog>
      <!--给用户分配角色对话框-->
      <el-dialog
          title="分配角色"
          :visible.sync="assignRoleDialogVisible"
          width="30%"
          @close="closeAssignRoleDialog">
        <div>
          <p>当前的用户：{{ userInfo.username }}</p>
          <p>当前的角色：{{ userInfo.role_name }}</p>
          <p>
            分配新角色：
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option
                  v-for="role in roleList"
                  :key="role.id"
                  :label="role.roleName"
                  :value="role.id"
                  @change="selectRoleId = role.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <el-form>

        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assignRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>

export default {
  name: "Users",
  data() {
    // 验证邮箱的规则
    let checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号的规则
    let checkMobile = (rule, value, cb) => {
      // 验证手机号的正则
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法的手机号
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }

    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 2
      },
      // 用户列表
      userList: [],
      // 总记录数
      total: 0,
      // 添加用户对话框是否显示
      addUserDialogVisible: false,
      // 添加用户表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则对象
      addUserFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 3, max: 10, message: '用户名的长度在3-10个字符之间', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
          {min: 6, max: 19, message: '密码的长度在6-19个字符之间', trigger: 'blur'}
        ],
        email: [
          // {required: true, type:'email', message: '邮箱不正确', trigger: 'blur'}
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      },
      // 修改用户信息对话框的显示
      editUserDialogVisible: false,
      // 保存修改用户信息
      editUserForm: {},
      editUserFormRules: {
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},
          {validator: checkEmail, trigger: 'blur'}
        ],
        mobile: [
          {required: true, message: '请输入手机号', trigger: 'blur'},
          {validator: checkMobile, trigger: 'blur'}
        ]
      },
      // 显示分配角色对话框
      assignRoleDialogVisible: false,
      // 当前需要被分配角色的用户信息
      userInfo: {},
      // 所有角色数据列表
      roleList: [],
      // 当前在分配角色下拉菜单中选中的角色Id
      selectRoleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo})

      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听 pageSize 事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页面值改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 改变用户的状态
    async userStateChanged(userInfo) {
      const {data: res} = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if (res.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更新用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 添加用户对话框关闭
    addUserDialogClosed() {
      this.$refs.addUserForm.resetFields()
    },
    // 点击按钮添加用户
    addUser() {
      this.$refs.addUserForm.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        // 可以发起添加用户的网络请求
        const {data: res} = await this.$http.post('users', this.addUserForm)

        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }

        this.$message.success('添加用户成功')
        // 隐藏对话框
        this.addUserDialogVisible = false
        // 加载新数据
        this.getUserList()
      })
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      // 根据ID获取用户信息
      const {data: res} = await this.$http.get(`users/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }

      this.editUserForm = res.data;

      this.editUserDialogVisible = true
    },
    // 关闭修改用户对话框重置信息
    editUserDialogClosed() {
      this.$refs.editUserForm.resetFields()
    },
    // 点击按钮修改用户信息
    editUser() {
      this.$refs.editUserForm.validate(async valid => {
        if (!valid) return
        // 可以发起修改用户的网络请求
        const {data: res} = await this.$http.put(
            `users/${this.editUserForm.id}`,
            {
              email: this.editUserForm.email,
              mobile: this.editUserForm.mobile
            })
        if (res.meta.status !== 200) {
          console.log(res)
          return this.$message.error('修改用户信息失败')
        }

        this.editUserForm = {}
        this.editUserDialogVisible = false
        this.getUserList()
        this.$message.success('修改用户信息成功')
      })
    },
    // 根据 Id 删除用户
    async removeUserById(id) {
      // 询问用户是否删除该用户
      const confirmRes = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err) // 当只有一行的时候，可以省略{return err}


      if (confirmRes !== 'confirm') {
        return this.$message.info('已取消删除')
      }

      const {data: res} = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.info('删除用户失败')
      }

      this.getUserList()
      this.$message.success('删除用户成功')
    },
    // 显示分配角色对话框
    async showAssignRoleDialog(userInfo) {
      this.userInfo = userInfo

      // 获取所有的角色列表
      const {data: res} = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色数据失败')
      }

      this.roleList = res.data

      // 初始化用户的角色ID
      this.roleList.forEach(role => {
        if (role.roleName === this.userInfo.role_name) {
          this.selectRoleId = role.id
        }
      })

      this.assignRoleDialogVisible = true
    },
    // 点击保存按钮分配角色
    async saveRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }

      const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`,
          {'rid': this.selectRoleId})
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }

      this.$message.success('分配角色成功')
      this.getUserList()
      this.assignRoleDialogVisible = false
    },
    // 关闭分配角色对话框
    closeAssignRoleDialog() {
      this.selectRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>

</style>